package com.hd.work0406.Controller;

import com.hd.work0406.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

@CrossOrigin
@Controller
@RequestMapping("/student")
public class TestController {

    @Autowired
    Student student;


    String [] stuName=null;
    int num=0;
    int length;
    @GetMapping("/raffle")
    @ResponseBody
    public String raffle() throws Exception {
        String name = null;
        Reader r = new FileReader(student.getPath());
        char[] ch = new char[1024];
        int index = 0;
        int len;
        while ((len = r.read(ch)) != -1) {
            name = new String(ch, 0, len);
        }
        if (num == 0){
            stuName = name.split(",");
            length=stuName.length;
            num++;
        }

        String [] newStuName=new String[length];

//       System.out.println(stuName.length);
        /*产生随机数*/
        index=(int)(Math.random()*length);
        /*将被抽同学加入新数组*/
        String names=stuName[index];
        num++;
        /*将被抽同学在旧数组删除*/
        for (int i = 0; i < length; i++) {
            if (stuName[index] == stuName[i]) {
                for (int j = index; j < length - 1; j++) {
                    stuName[j] = stuName[j + 1];
                }
                length--;
                break;
            }
        }
        for (int i = 0; i <length; i++) {
            newStuName[i]=stuName[i];
            System.out.println("输出删除后旧数组有的名字" + newStuName[i] + i);

        }
        System.out.println(index);
        System.out.println(names);
        //关闭流
        r.close();
        return names;
    }
    @GetMapping("/reset")
    @ResponseBody
    public String reset() throws Exception {
        String name = null;
        Reader r = new FileReader(student.getPath());
        num = 0;
        char[] ch = new char[1024];
        int len;
        while ((len = r.read(ch)) != -1) {
            name = new String(ch, 0, len);
        }
        stuName = name.split(",");
        for (String s : stuName) {
            System.out.println(s);
        }
        //关闭流
        r.close();
    return stuName.length==25?"重置成功":"重置失败";
    }

}
